package com.app.controller;

import com.app.model.AdminUserModel;
import com.app.model.CategoryModel;
import com.app.model.CategoryPhoneModel;
import com.app.model.DepartmentModel;
import com.app.service.AdminUserService;
import com.app.service.CategoryPhoneService;
import com.app.service.CategoryService;
import com.app.util.CommonHelp;
import com.app.util.Result;
import com.app.util.TokenUtils;
import com.app.vo.CategoryVo;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;

@RestController
@Controller
@RequestMapping("/api/phoneData")
public class CategoryPhoneController {
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private CategoryPhoneService categoryPhoneService;
    @Autowired

    private AdminUserService adminUserService;

    @GetMapping("/getPhoneTree")//手机公共数据管理树
    public Result<Object> getPhoneTree(
            @RequestParam("name") String name,
            HttpServletRequest request) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        AdminUserModel user = adminUserService.getUserByUserId(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
//        List<CategoryModel> catModelList = categoryService.selectPerTree(name);//全查
        List<CategoryPhoneModel> categoryPhoneModelList = categoryPhoneService.selectPhoneTree(name);//全查
        if(categoryPhoneModelList == null){
            return Result.error(200,"暂无数据");
        }

        List<Integer> arr1 = new ArrayList<>();
        for (int i = 0; i < categoryPhoneModelList.size(); i++) {
            arr1.add(categoryPhoneModelList.get(i).getId());
        }
        Integer ArrId = 1;
        boolean result1 = arr1.contains(ArrId);
        List<Integer>pidArr1 = new ArrayList<>();
        if(!result1){
            for (int i = 0; i < categoryPhoneModelList.size(); i++) {

                boolean PidResult = arr1.contains(categoryPhoneModelList.get(i).getPid());
                if(!PidResult){
                    pidArr1.add( categoryPhoneModelList.get(i).getPid());
                }
            }
            pidArr1.add(ArrId);
            arr1.addAll(pidArr1);
            LinkedHashSet<Integer> hashSet = new LinkedHashSet<>(arr1);
            ArrayList<Integer> listWithoutDuplicates = new ArrayList<>(hashSet);
             List<CategoryPhoneModel> catModelList1 = new ArrayList<>();
            for (int i = 0; i < listWithoutDuplicates.size(); i++) {

                CategoryPhoneModel categoryModel = categoryPhoneService.getCategoryPhoneById(listWithoutDuplicates.get(i));
                catModelList1.add(categoryModel);
            }
            return Result.success(findChildren(catModelList1,0));
        }
        return Result.success(findChildren(categoryPhoneModelList,0));
    }
    private List<CategoryPhoneModel> findChildren(List<CategoryPhoneModel> modelList, Integer pid){//递归方法
        List<CategoryPhoneModel> personModelList= new ArrayList<>();
        for (int i = 0; i < modelList.size(); i++) {
            if(modelList.get(i).getPid() == pid)
            {
                CategoryPhoneModel model = modelList.get(i);
                List<CategoryPhoneModel> modelList1 = findChildren(modelList,model.getId());
                for (int j = 0; j < modelList1.size(); j++) {
                    if(modelList1!=null&&modelList1.size()>0)
                    {
                        model.setChild(modelList1);
                    }
                }
                personModelList.add(model);
            }
        }
        return personModelList;
    }

    @GetMapping("/getCategoryList")//数据管理分页查询
    public Result<Object> getCategoryList(
            @RequestParam("page") int page,
            @RequestParam("limit") int limit,
            @RequestParam(required = false) String name,
            HttpServletRequest request) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        AdminUserModel user = adminUserService.getUserByUserId(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        Page<CategoryModel> categoryModelPage = categoryService.categoryPageList(page,limit,name);
        if(categoryModelPage == null){
            return Result.error(200,"暂无数据");
        }
        int count = (int)categoryModelPage.getTotal();
        List<CategoryModel> categoryModelList;
        categoryModelList = categoryModelPage.getRecords();
        CategoryVo vo = new CategoryVo();
        vo.setList(categoryModelList);
        vo.setCount(count);
        return Result.success(vo);
    }
    @PostMapping("/insertAndUpdatePhone")//    新增/修改手机数据管理
    public Result<Object> insertAndUpdatePhone(
            @RequestParam("id") Integer id,
            @RequestParam("pid") Integer pid,
            @RequestParam("name") String name,
            @RequestParam("sort") Integer sort,
            @RequestParam("status") Integer status,
            HttpServletRequest request) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        AdminUserModel user = adminUserService.getUserByUserId(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        CategoryPhoneModel model = new CategoryPhoneModel();
        model.setId(id);
        model.setPid(pid);
        model.setName(name);
        model.setSort(sort);
        model.setStatus(status);
        try{
            if(id > 0){
                model.setId(id);
                model.setUpdateTime(CommonHelp.getNowTimestamp());
                categoryPhoneService.update(model);
            }else {
                model.setCreateTime(CommonHelp.getNowTimestamp());
                categoryPhoneService.insert(model);
            }
        }catch (Exception e){
            System.out.println(e);
        }
        return Result.success(null);
    }
    @GetMapping("/updatePhoneStatus")//修改状态
    public Result<Object> updatePhoneStatus(
            @RequestParam("id") Integer id,
            @RequestParam("status") Integer status,
            HttpServletRequest request) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        AdminUserModel user = adminUserService.getUserByUserId(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        CategoryPhoneModel model = new CategoryPhoneModel();
        model.setId(id);
        model.setStatus(status);
        categoryPhoneService.update(model);
        List<CategoryPhoneModel> categoryPhoneModelList = categoryPhoneService.getPhoneListByPid(id);
        if(categoryPhoneModelList==null && categoryPhoneModelList.size()>0){
            return Result.success(null);
        }
        for (int i = 0; i < categoryPhoneModelList.size(); i++) {
            CategoryPhoneModel phoneModel = new CategoryPhoneModel();
            phoneModel.setId(categoryPhoneModelList.get(i).getId());
            phoneModel.setStatus(status);
            categoryPhoneService.update(phoneModel);
        }
        return Result.success(null);
    }
    @GetMapping("/deleteById")//删除数据
    public Result<Object> deleteById(
            @RequestParam("id") Integer id,
            HttpServletRequest request) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        AdminUserModel user = adminUserService.getUserByUserId(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        CategoryPhoneModel model  = categoryPhoneService.getCategoryPhoneById(id);
        if(model == null){
            return Result.error(500,"该条数据不存在");
        }else {
            categoryPhoneService.delete(id);
            return Result.success(null);
        }
    }

}
